package com.xx.phonecall;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.stkcall.library.CallPhoneManager;
import com.stkcall.library.CallState;
import com.stkcall.library.CallStateListener;
import com.stkcall.library.DeviceUtils;
import com.stkcall.library.PhoneInfo;
import com.stkcall.library.RecordAudioManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private EditText edit_phone;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit_phone = findViewById(R.id.edit_phone);

        //初始化拨打管理
        CallPhoneManager.getInstance().init(this);
        //初始化录音管理
        RecordAudioManager.getInstance().init(this);
//        RecordAudioManager.getInstance().deInit();

        //设置查询文件列表的最大值 -1为全量 默认50
        RecordAudioManager.getInstance().setFileListMaxValue(-1);
        //设置录音开关Key
//        RecordAudioManager.getInstance().setRecordAudioKey("call_record_state_global");
        //设置录音设置页启动路径
//        RecordAudioManager.getInstance().setRecordAudioSetting("com.android.phone/com.android.phone.AsusAdvancedSubSettingsActivity");
        //设置查询录音路径
        RecordAudioManager.getInstance().setRecordSearchAudioFile("/MIUI/sound_recorder/call_rec");
        //时间节点
//        Calendar instance = Calendar.getInstance();
//        instance.set(2022,5,10);
        //设置查询录音时间节点
//        RecordAudioManager.getInstance().setRecordTimeNode(instance.getTimeInMillis());
        //权限判断
//        boolean grantedAllPermission = RecordAudioManager.getInstance().isGrantedAllPermission();
//        RecordAudioManager.getInstance().setOnPermissionCallback(new com.hjq.permissions.OnPermissionCallback() {
//            @Override
//            public void onGranted(List<String> permissions, boolean all) {
//
//            }
//
//            @Override
//            public void onDenied(List<String> permissions, boolean never) {
//
//            }
//        });

        //设置通话状态监听
        CallPhoneManager.getInstance().addCallStateListener(listener);
    }

    private CallStateListener listener = new CallStateListener() {
        @Override
        public void CallState(Context context, CallState state, String phoneNumber,long duration) {
            Log.d("test", "updateState: " + state);

            if(state == CallState.CALL_IDLE){
                List<File> files = RecordAudioManager.getInstance().searchAudioFile();
                Toast.makeText(context, "有" + files.size() + "录音", Toast.LENGTH_SHORT).show();
            }
            if(state == CallState.CALL_HANG_UP){
                Toast.makeText(context, "挂断", Toast.LENGTH_SHORT).show();
                searchAudio();
            }
            if(state == CallState.CALL_IN){
                Toast.makeText(context, "来电", Toast.LENGTH_SHORT).show();
            }
            if(state == CallState.CALL_OUT){
                Toast.makeText(context, "去电", Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 查询录音文件
     */
    private void searchAudio() {
        File file = RecordAudioManager.getInstance().searchAudioLastFile();
        if(file != null) {
            Log.d(TAG, "searchAudio: " + file.toString());
        }

        showDialog(file);
    }

    private void showDialog(File path){
        if(path == null || isFinishing()) return;

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("最近一次通话")
                .setMessage(path.getPath())
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        RecordAudioManager.getInstance().deleteFile(path);
                    }
                })
                .create();
        dialog.show();
    }

    /**
     * 拨打电话
     * @param view
     */
    public void CallPhone(View view) {
        List<PhoneInfo> simInfo = DeviceUtils.getSimInfo(this);
        StringBuilder sb = new StringBuilder();
        for (PhoneInfo i : simInfo){
            sb.append("卡");
            sb.append(i.simId);
            sb.append(":");
            sb.append(i.simSerialNumber);
            sb.append("\n");
        }
        Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();

        //1开启 0未开启 -1未检查到
//        if(RecordAudioManager.getInstance().checkRecordAudioSwitch(this) == 1){
            CallPhoneManager.getInstance().callNumber(this,edit_phone.getText().toString(),"");
//        }else {
//            showOpenRecordAudio();
//        }

    }

    private void showOpenRecordAudio() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("请求开启录音权限")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        RecordAudioManager.getInstance().openSetting(MainActivity.this);
                    }
                })
                .create();
        dialog.show();
    }

    public void getSimInfo1(View view) {
        List<PhoneInfo> simInfo1 = DeviceUtils.getSimInfo1(this);
        StringBuilder sb = new StringBuilder();
        for (PhoneInfo i:simInfo1){
            sb.append(i.simSerialNumber);
            sb.append("\n");
        }
        Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
    }

    public void getSimInfo2(View view) {
        List<PhoneInfo> simInfo1 = DeviceUtils.getSimInfo2(this);
        StringBuilder sb = new StringBuilder();
        for (PhoneInfo i:simInfo1){
            sb.append(i.simSerialNumber);
            sb.append("\n");
        }
        Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
    }

    public void getSimInfo3(View view) {
        List<PhoneInfo> simInfo1 = DeviceUtils.getSimInfo3(this);
        StringBuilder sb = new StringBuilder();
        for (PhoneInfo i:simInfo1){
            sb.append(i.simSerialNumber);
            sb.append("\n");
        }
        Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CallPhoneManager.getInstance().removerCallStateListener(listener);
    }

    public void searchLatestAudio(View view) {
        startActivity(new Intent(this,AudioActivity.class));
    }
}